import 'dart:html';
import 'dart:uri';
import '../lib/src/cache/cache.dart';
import '../lib/src/compiler/compiler.dart';

part 'page.dart';

final Page page = new Page(run);

/// Main entry point... prepopulate code and add listeners
void main() {
  page.dartSource = '''
void main() {
  print("Hello Dart!");
}
''';
}

/// Called when user clicks the run button
run(Event event) {
  page
    ..clearLog()
    ..status = 'Compiling...';
  compile(
      new Uri('cache://user/script.dart'),
      new Uri('libraryRoot'),
      new Uri('packageRoot'),
      getSource,
      logInfo).then(compiled);
}
compiled(jsSource) {
  logMessage('');
  logMessage(jsSource);
  page.status = '';
  print(jsSource);
}

/// Answer the source for the specified URI
Future<String> getSource(Uri uri) {
  return new Future.immediate(getCode(uri));
}
String getCode(Uri uri) {
  if (uri.toString() == 'cache://user/script.dart') return page.dartSource;
  String code = CACHE[uri.toString()];
  if (code != null) return code;
  logMessage('Failed to find source for ${uri.toString()}');
  return '';
}

/// Called with compilation information
void logInfo(Uri uri, int begin, int end, String message, Diagnostic kind) {
  if (uri != null) {
    logMessage('$uri [$begin, $end]');
  }
  logMessage(message);
}
void logMessage(String message) {
  print(message);
  page.log(message);
}